package com.yunyi.user.controller;
import com.alibaba.fastjson.JSONObject;
import com.yunyi.response.CommonCode;
import com.yunyi.response.ResponseResult;
import com.yunyi.user.constant.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName WxUserController
 * @Description 微信接口调用接口
 * @Author leizhang
 * Date 2021/8/18 12:13 上午
 * @Version 1.0
 **/
@RestController
@RequestMapping("/wxApi")
public class WxUserController {
    private static Logger LOGGER = LoggerFactory.getLogger(WxUserController.class);
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    @Value("${weixin.access-token-base-url}")
    private String wxAccessTokenBaseUrl;
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/auth")
    public ResponseResult loginAppKey(@RequestParam String code) {
        if (StringUtils.isBlank(code))  {
            return new ResponseResult(CommonCode.CODE_FAIL);
        }
        ResponseResult responseResult = null;
        JSONObject result = null;
        try {
            String url = new StringBuffer(wxAccessTokenBaseUrl).append("appid=").append(appid).append("&secret=").append(secret).append("&js_code=")
                    .append(code).append("&grant_type=authorization_code").toString();
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            result = JSONObject.parseObject(forEntity.getBody().toString());
        }catch (Exception e){
            LOGGER.error("调用微信登录接口错误:[{}]",e.getMessage(),e);
        }
        if (null != result.get(Constant.ERR_CODE)) {
            responseResult = new ResponseResult(CommonCode.WX_ERR_CODE);
            responseResult.setMessage(result.get(Constant.ERR_MESG).toString());
            return responseResult;
        }
        if (null == result.get(Constant.OPENID)) {
            return new ResponseResult(CommonCode.WX_ERR_OPENID);
        }
        responseResult = new ResponseResult(CommonCode.SUCCESS);
        responseResult.setMessage(result.toString());
        return responseResult;
    }
}
